package base;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.List;
import org.jdom.Document;
import org.jdom.Element;
import org.jdom.JDOMException;
import org.jdom.input.SAXBuilder;

/**
 * This class provides a static method for retrieving the TV shows info from the EzTV RSS feed.
 * @author Tácio Rocha
 */
public class Feed {

    /**
     * The following static method returns a collection of all the &lt;item&gt;
     * elements in the RSS feed where the TV shows infos can be found.
     * 
     * @param rssUrl An absolute URL giving the location of a .rss file.
     * @return a List&lt;Element&gt; object
     */
    public static List<Element> getRssItems(String rssUrl) throws MalformedURLException, IOException, JDOMException {

        //creates an URL from the method call
        URL url = new URL(rssUrl);

        //Instantiates a BufferedReader in which encapsulates the url.openstream InputStreamReader
        BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream()));

        /*
         *Now we play with JDOM and create a SAXBuilder
         * which will then build the xml Document model from the BufferedReader in
         */
        SAXBuilder builder = new SAXBuilder();
        Document xmlDoc = builder.build(in);
        in.close();

        /*
         * Now we get the <chanel> Element, under whom all the <item> Elements are nested
         */
        Element channel = xmlDoc.getRootElement().getChild("channel");

        /*
         * Finally, we create a typed List of <item> elements from which we can do almost anything
         * from simply displaying the RSS feed items in any format or, better, look for the
         * newest release of our favorite TV shows!
         */
        List<Element> itemList = channel.getChildren("item");
        return itemList;
    }
}
